import { SHORT_DATE_TIME_FORMAT } from '@/constants';
import { type DetailResult, type ObsMaterial } from '@/pages/types/type';
import { getRequestInit, obsPrifix, urlPrefix } from '@/utils/http';
import { useNavigate } from 'alita';
import { Dialog, Divider, DotLoading, Image, ImageViewer } from 'antd-mobile';
import {
  ArrowDownCircleOutline,
  DownOutline,
  InformationCircleOutline,
  UpOutline,
} from 'antd-mobile-icons';
import dayjs from 'dayjs';
import React, { FC, useEffect, useState } from 'react';

import { DeleteButton } from '../delete';
import { UploadObjectObsMaterial } from '../upload';
import styles from './index.less';
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp'];

const Single: FC<{ name: string; src: string }> = ({ name, src }) => {
  const [visible, setVisible] = useState(false);
  return (
    <>
      <span
        onClick={() => {
          setVisible(true);
        }}
      >
        {name}
      </span>
      <ImageViewer
        classNames={{
          mask: 'customize-mask',
          body: 'customize-body',
        }}
        image={src}
        visible={visible}
        onClose={() => {
          setVisible(false);
        }}
      />
    </>
  );
};

const DownloadButton: FC<{ obsKey: string }> = ({ obsKey }) => {
  const prefix = obsKey.split('.').pop()!.toLowerCase();
  const isImage = imageExtensions.includes(prefix);
  const src = `${obsPrifix}/${encodeURIComponent(obsKey)}`;
  const [visible, setVisible] = useState(false);
  return !isImage ? (
    <ArrowDownCircleOutline
      onClick={(e) => {
        window.open(src);
        e.stopPropagation();
      }}
    />
  ) : (
    <>
      <ArrowDownCircleOutline
        onClick={() => {
          setVisible(true);
        }}
      />

      <ImageViewer
        classNames={{
          mask: 'customize-mask',
          body: 'customize-body',
        }}
        image={src}
        visible={visible}
        onClose={() => {
          setVisible(false);
        }}
      />
    </>
  );
};

export const ObsMaterials: FC<{
  title?: string;
  url: string;
  id: number | string;
  marginTop?: string | number;
  titleBold?: boolean;
  supportHide?: boolean;
  hideFirst?: boolean;
}> = ({ title, url, id, titleBold = false, hideFirst, supportHide }) => {
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(1);
  const [obsMaterials, setObsMaterials] = useState<ObsMaterial[]>([]);
  const [hide, setHide] = useState<boolean>(hideFirst || false);
  const navigate = useNavigate();
  function load() {
    let times = 1;
    fetch(`${urlPrefix}${url}/get-by-source/${id}`, getRequestInit())
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          await rsp
            .json()
            .then(({ data, code, msg }: DetailResult<ObsMaterial[]>) => {
              if (code === 0) {
                if (data) {
                  setObsMaterials(data);
                }
                setLoadOK(msg);
              } else {
                setLoadFails([...loadFails, msg]);
              }
            })
            .catch((reason) => {
              setLoadFails([...loadFails, reason]);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setLoadFails([...loadFails, `加载附件信息时发生错误：${reason}`]);
      })
      .finally(() => {
        setLoadingTimes(--times);
      });
  }
  useEffect(load, [url, id]);
  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>
          正在载入附件信息{url},id={id}
        </span>
      </div>
    );
  }
  return (
    <div className={styles.wrap}>
      <div
        className={styles.title}
        style={{
          fontSize: 14,
          fontWeight: titleBold ? 800 : '',
        }}
      >
        {supportHide && (
          <>
            {hide && <DownOutline onClick={() => setHide(false)} />}
            {!hide && <UpOutline onClick={() => setHide(true)} />}
          </>
        )}
        {title || '附件'}({obsMaterials.length})
        <Divider direction={'vertical'} />
        <UploadObjectObsMaterial
          url={url}
          source={id}
          onSuccess={load}
          title={`增加${title}`}
          label="材料/附件"
        />
      </div>

      {!hide && (
        <div className={styles.list}>
          {obsMaterials.map(
            ({ createdAt, creator, thumb, name, obsKey, remark, id }) => {
              const prefix = obsKey.split('.').pop()!.toLowerCase();
              const isImage = imageExtensions.includes(prefix);
              const src = `${obsPrifix}/${encodeURIComponent(obsKey)}`;
              return (
                <React.Fragment key={id}>
                  <div
                    className={styles.item}
                    style={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                    }}
                  >
                    <div className={styles.left}>
                      {
                        <Image
                          src={`${obsPrifix}/${
                            thumb || encodeURIComponent(obsKey)
                          }`}
                          fit="fill"
                          width={40}
                          height={'100%'}
                          onClick={() => {}}
                        />
                      }
                      <div className={styles.info}>
                        <div className={styles.name}>
                          {!isImage ? (
                            <a
                              key={id}
                              rel="noreferrer"
                              target="_blank"
                              href={src}
                            >
                              {name}
                            </a>
                          ) : (
                            <Single name={name} src={src} />
                          )}
                        </div>
                        <div className={styles.time}>
                          {dayjs(createdAt).format(SHORT_DATE_TIME_FORMAT)}| (
                          {creator.name})
                        </div>
                      </div>
                    </div>
                    <div className={styles.right}>
                      <DeleteButton
                        url={`${url}/delete/${id}`}
                        onSuccess={load}
                      />
                     
                      <InformationCircleOutline
                        style={{marginLeft:'5px',marginRight:'5px'}}
                        onClick={() => {
                          Dialog.alert({
                            title: '附件信息',
                            content: (
                              <>
                                <div>创建：{creator.name}</div>
                                <div>备注：{remark}</div>
                              </>
                            ),
                          });

                          //navigate(`/pdf-viewer?obsKey=${encodeURIComponent(obsKey)}`)
                        }}
                      />
                     
                      <DownloadButton obsKey={obsKey}  />
                    </div>
                  </div>
                </React.Fragment>
              );
            },
          )}
        </div>
      )}
    </div>
  );
};
